package logic;

import java.io.Serializable;

/**
 * 
 * @author Marco Gallardo Casu
 * 
 */
public class Sudoku implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -56335590432818866L;

	public static final int LENGTH = 9;

	private String name;
	private Square[] squares;

	public Sudoku() {
		this.name = "New Sudoku";
		squares = new Square[LENGTH];
		for (int index = 0; index < LENGTH; index++) {
			squares[index] = new Square();
		}
	}

	public Sudoku(String name, Square[] squares) {
		this.name = name;
		this.squares = squares;
	}

	public Sudoku(int[][] genes) {
		this.squares = getSquares(genes);
	}

	public String getName() {
		return name;
	}

	public Square[] getSquares() {
		return squares;
	}

	public Square[] getSquares(int[][] genes) {
		Square[] squares = new Square[LENGTH];
		for (int index = 0; index < LENGTH; index++) {
			squares[index] = new Square(genes[index]);
		}
		return squares;
	}

	public Square getSquare(int index) {
		if (index < 0 || index >= LENGTH) {
			return null;
		} else {
			return squares[index];
		}
	}

	public void setSquares(Square[] squares) {
		this.squares = squares;
	}

	public void setSquare(Square square, int index) {
		squares[index] = square;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null || !(obj instanceof Sudoku)) {
			return false;
		} else if (this == obj) {
			return true;
		} else {
			Sudoku sudoku = (Sudoku) obj;
			boolean equals = true;
			for (int index = 0; equals && index < LENGTH; index++) {
				equals = sudoku.getSquare(index).equals(squares[index]);
			}
			return equals;
		}
	}

	@Override
	public Object clone() {
		try {
			Square[] squares = new Square[LENGTH];
			for (int index = 0; index < LENGTH; index++) {
				for (int col = 0; col < LENGTH; col++) {
					squares[index] = (Square) getSquare(index).clone();
				}
			}
			return new Sudoku(getName(), squares);
		} catch (CloneNotSupportedException e) {
			System.err.println(e.getMessage());
		}
		return null;
	}

}
